var db = require('../../db/db');
var publictool = require("../../publictool/publictool");

exports.port = function (req, res) {
    var requestData = '';
    req.addListener('data', function (postDataChunk) {
        requestData += postDataChunk;
    });

    req.addListener('end', function () {
        publictool.putlog(req, requestData);
        var phone = publictool.checkoutdata(res, requestData);
        if (!phone) {
            return;
        }

        var client = db.client();
        db.checkuser(client, res, false, phone.accesstoken)
            .then(function (resultvalue) {
                getreceipt(phone, res, client);
            });
    });
};

function getreceipt(phone, res, client) {
    var sql = 'SELECT * FROM receipt where product_index=?';
    var addSqlParams = [phone.product_index];

    client.query(sql, addSqlParams, function (err, result) {
        if (err) {
            publictool.returnErr(res, '查询参数错误:' + '[SELECT ERROR] - ' + err.message, 1);
            client.end();
            return;
        }

        if (result.length > 0) {
            updatedata(phone, res, client);
        } else {
            publictool.returnErr(res, '未找到票据:' + phone.product_index, 1);
            client.end();
            return;
        }
    });
}

function updatedata(phone, res, client) {

    var modSql = 'UPDATE receipt SET status = ? ,msg = ? WHERE product_index = ?';
    var modSqlParams = [phone.status, phone.msg,phone.product_index];

    client.query(modSql, modSqlParams, function (err, result) {
        if (err) {
            publictool.returnErr(res, '更新参数错误:' + '[UPDATE ERROR] -' + err.message, 1);
            client.end();
            return;
        }

        publictool.returnErr(res, '操作成功', 0);
        client.end();
        return;
    });
}